<template>
  <a-modal v-model:visible="visible" @ok="handleOk" @cancel="handleCancel" width="100%" wrapClassName="full-modal" okText="确定添加">
    <div class="title">
      标题：
      <span @click="editTitle" contenteditable @input="change" @blur="blur" id="title">
        {{ processData.process_name }}
      </span>
    </div>

    <div class="wrap">
      <div v-for="(item, index) in processData.items" :key="index">
        <div class="item">
          <edit-item :index="index" :infoData="item" :isDisabled="isDisabled" @removeItem="removeItem(index)" @addItem="addNextItem(index)" ref="resetChild" />
        </div>
      </div>
    </div>
  </a-modal>
</template>
<script lang="ts">
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import 'ant-design-vue/es/message/style/css'
import { createVNode, defineComponent, ref, toRaw, reactive, computed } from 'vue'
import { Modal } from 'ant-design-vue'
import EditItem from '../../../components/process/AddItem.vue'
import { post } from '../../../utils/request/request'

interface FormState {
  process_name: string
  items: {
    title: string
    date: string
    type: number | undefined
    event_id: number | undefined
    number: number | undefined
    status: number | undefined
  }[]
}

const processData: FormState = reactive({
  process_name: '点击此处编辑标题',
  items: [
    {
      title: '', //事件名称
      date: '', //事件日期
      type: undefined, //事件类型：1.报名 2.面试 3.其他事件
      event_id: undefined, //时间ID，类型为面试时是面试id，问卷时是问卷id
      number: undefined,
      status: undefined //状态：0.未开始，1.进行中，2.已结束
    }
  ]
})

const useRefChildEffect = () => {
  const resetChild = ref()
  const resetForm = () => {
    processData.process_name = '点击此处编辑标题'
    resetChild.value.reset()
  }
  return { resetChild, resetForm }
}

const useModalEffect = (processData: FormState, token: string, emit: any) => {
  const { resetChild, resetForm } = useRefChildEffect()
  const visible = ref<boolean>(false)
  const showModal = () => {
    visible.value = true
  }
  const handleOk = async () => {
    const items = processData.items
    const title = processData.process_name
    for (let i = 0; i < items.length; i++) {
      items[i].number = i + 1
    }
    console.log(toRaw(processData))
    if (title && title != '点击此处编辑标题') {
      let isFilled = items.every((item: any) => Object.keys(item).every((i) => item[i]))
      if (isFilled) {
        const res: any = await post('/admin/api/v1/recruitment/process', toRaw(processData), token)
        console.log(toRaw(processData))
        if (res.status_code === 0) {
          message.success('添加成功')
          console.log(toRaw(processData))
          console.log(res)
          const addDetail = {
            id: res.data.id as number,
            name: processData.process_name
          }
          emit('add', addDetail)
          visible.value = false
          resetForm()
        } else {
          message.warn('添加失败')
        }
      } else {
        message.warn('请填写完整')
      }
    } else {
      message.warn('请输入流程名称')
    }
  }
  const handleCancel = () => {
    let isValue = false
    if (processData.process_name && processData.process_name != '点击此处编辑标题') {
      isValue = true
    } else {
      isValue = processData.items.some((item) => {
        if (item.date || item.type || item.title || item.status || item.event_id) {
          return true
        } else {
          return false
        }
      })
    }
    if (isValue) {
      Modal.confirm({
        title: '你关闭了编辑窗口，请问要清除已填写的数据吗？',
        icon: createVNode(ExclamationCircleOutlined),
        content: createVNode('div', { style: 'color:red;' }, '点击确定后将全部清空，如果不想清空请点击取消'),
        onOk() {
          resetForm()
        },
        onCancel() {
          message.info('数据已保存，页面刷新前有效')
        }
      })
    }
  }
  return {
    visible,
    showModal,
    handleOk,
    handleCancel,
    resetChild
  }
}

const useEditTitleEffect = () => {
  const editTitle = () => {
    if (processData.process_name == '点击此处编辑标题') {
      processData.process_name = ''
    }
  }
  const change = () => {
    let title = document.getElementById('title')?.innerText as string
    if (title.length < 10) {
      processData.process_name = title
    } else {
      message.error('输入的字数太多了，只取前10个字')
    }
  }
  const blur = () => {
    if (!processData.process_name) {
      processData.process_name = '点击此处编辑标题'
    }
  }
  return { editTitle, change, blur }
}

const useEmitEffect = () => {
  const removeItem = (index: number) => {
    processData.items.splice(index, 1)
  }
  const addNextItem = (index: number) => {
    const newItem = {
      title: '', //事件名称
      date: '', //事件日期
      type: undefined, //事件类型：1.报名 2.面试 3.其他事件
      event_id: undefined, //时间ID，类型为面试时是面试id，问卷时是问卷id
      number: undefined,
      status: undefined //状态：0.未开始，1.进行中，2.已结束
    }
    processData.items.splice(index + 1, 0, newItem)
  }
  return { removeItem, addNextItem }
}

export default defineComponent({
  components: {
    EditItem
  },
  emits: ['add'],
  setup(props, { emit }) {
    const token: string = localStorage.getItem('token') as string
    const { editTitle, change, blur } = useEditTitleEffect()
    const { visible, showModal, handleOk, handleCancel, resetChild } = useModalEffect(processData, token, emit)
    const { removeItem, addNextItem } = useEmitEffect()

    return {
      blur,
      editTitle,
      visible,
      showModal,
      handleOk,
      handleCancel,
      resetChild,
      change,
      removeItem,
      processData,
      addNextItem,
      isDisabled: computed(() => (processData.items.length > 1 ? false : true))
    }
  }
})
</script>

<style lang="less">
.full-modal {
  .ant-modal {
    max-width: 100%;
    top: 0;
    padding-bottom: 0;
    margin: 0;
  }
  .ant-modal-content {
    display: flex;
    flex-direction: column;
    height: calc(100vh);
    overflow-y: auto;
    overflow-x: hidden;
  }
  .ant-modal-body {
    flex: 1;
  }
}
.ant-tabs-tab {
  max-width: 200px;
  // padding: 0 10px;
  overflow-x: auto; //超出的文本隐藏
  text-overflow: ellipsis;
  &::-webkit-scrollbar {
    /*滚动条整体样式*/
    width: 0px; /*高宽分别对应横竖滚动条的尺寸*/
    height: 0px;
  }
}
.title {
  font-size: 30px;
  text-align: center;
  margin: 20px 0 10px 0;
  padding-bottom: 20px;
  border-bottom: 1px solid #c8c8c8;
}
// 去除默认outline
[contenteditable]:focus {
  outline: none;
}
.item {
  border: 1px solid #c8c8c8;
  border-radius: 10px;
  padding-top: 20px;
  margin: 10px 10px 0 10px;
}
</style>
